<?php
	
	/**
	 * @author Jaroslaw (jareeny) Reglinski
	 * @copyright 2009 Jaroslaw Reglinski
	 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License v3
	 * @version 1.0
	 */

class nipValidator {
    	
	/**
	 * NIP Number
	 * 
	 * @var int
	 * @access private
	 */
	
	private $nip;
	
	/**
	 * Correct NIP number
	 * 
	 * @var bool
	 * @access private
	 */
	
	private $correct;
	
	/**
	 * Weight array for NIP number
	 * 
	 * @var array
	 * @access private
	 */
	
	private $weight = array(
	6,
	5,
	7,
	2,
	3,
	4,
	5,
	6,
	7
	);
	
	/**
	 * Errors in actual request
	 * 
	 * @var array
	 * @access private
	 */
	
	private $requersErr = array();
	
	/**
	 * Error codes and messages
	 * 
	 * @var array
	 * @access private
	 */
	
	private $error = array(
	0 => 'Ten numer NIP ma nieprawidłową ilość znaków',
	1 => 'Ten numer NIP jest nieprawidłowy'
	);
	
	/**
	 * 
	 */
	
	public function __construct($string = null) {
		
		if($string) {
			$this->check($string);
		}
		
	}
	
	/**
	 * Set a NIP number and evoke it check
	 * 
	 * @return void
	 * @param $string string
	 */
	
	public function check($string) {
		$string = (string)$string;
		$this->correct = false;
		if(is_numeric($string)) {
			if(strlen($string) !== 10) {
				$this->handleError(0);
			}
			$this->nip = $string;
			$this->checkControlsum();
		}
	}
	
	/**
	 * Check a NIP number
	 * 
	 * @return void
	 */
	
	private function checkControlsum() {
		$controlSum = 0;
		for($i = 0; $i <= 8; $i++) {
			$controlSum += $this->nip[$i] * $this->weight[$i];
		}
		$controlNumber = $controlSum % 11;
		if($this->nip[9] == $controlNumber) {
			$this->correct = true;
			return;
		}
		$this->handleError(1);
		$this->correct = false;
		return;
    }
	
	/**
	 * 
	 * @return bool
	 */
	
	public function isValid() {
		if($this->correct) {
			return true;	
		}
		return false;	
	}
	
	/**
	 * Return a NIP number
	 * 
	 * @return string
	 */
	
	public function getNip() {
		return $this->nip;
	}
	
	/**
	 * Handle an errors
	 * 
	 * @return void
	 * @param $errorCode integrer
	 */
	
	private function handleError($errorCode) {
		if(isset($this->error[$errorCode])) {
			$this->requestErr[]=$this->error[$errorCode];
		}	
	}
	
	/**
	 * Return a errors array
	 * 
	 * @return array
	 */
	
	public function hasError() {
		if(!empty($this->requestErr)) {
			return true;	
		}
		return false;
	}
	
	/**
	 * Return a errors array
	 * 
	 * @return array 
	 */
	
	public function getError() {
		return $this->requestErr;
	}
	
}

?>
